import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElSelect,
  ElOption
} from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

export default defineComponent({
  props: ['cancel', 'record'],
  emits: ['submitForm'],
  setup(props, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive(
      Object.assign(
        {
          estDiscount: 0,
          delistingIndx: 0
        },
        props?.record?.id
          ? {
              estDiscount: props.record.estDiscount,
              delistingIndx: props.record.delistingIndx
            }
          : {}
      )
    )
    const rules = reactive<FormRules>({
      estDiscount: [{ required: true, message: '输入预计折扣率', trigger: 'blur' }],
      delistingIndx: [{ required: true, message: '请选择摘牌优先级', trigger: 'change' }]
    })
    //  修改密码
    const submitForm = () => {
      ruleFormRef.value?.validate(async (valid) => {
        if (valid) {
          const { code } = await store.dispatch('base/GetBasebuildbatchUpdateDelisting', {
            ...ruleForm,
            assetBaseBuildId: props.record.id
          })
          if (code === 200) {
            ElMessage({
              message: '操作成功',
              type: 'success'
            })
            emit('submitForm')
            props.cancel()
          }
        }
      })
    }
    //  取消
    const resetForm = () => {
      // ruleFormRef.value?.resetFields()
      props.cancel()
    }

    return () => (
      <ElDialog
        title="加入摘牌库"
        modelValue={true}
        beforeClose={props.cancel}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        width={450}
        v-slots={{
          footer: () => (
            <>
              <ElButton onClick={resetForm}>取消</ElButton>
              <ElButton type="primary" onClick={submitForm}>
                确定
              </ElButton>
            </>
          )
        }}
      >
        <ElForm ref={ruleFormRef} model={ruleForm} rules={rules}>
          <ElFormItem prop="estDiscount">
            <ElInput
              v-model={ruleForm.estDiscount}
              placeholder="请输入预计折扣率0 ~ 100"
              v-slots={{
                append: () => <div>%</div>
              }}
            ></ElInput>
          </ElFormItem>
          <ElFormItem prop="delistingIndx">
            <ElSelect v-model={ruleForm.delistingIndx} placeholder="请选择摘牌优先级">
              <ElOption label="1" value={1}></ElOption>
              <ElOption label="2" value={2}></ElOption>
              <ElOption label="3" value={3}></ElOption>
            </ElSelect>
          </ElFormItem>
        </ElForm>
      </ElDialog>
    )
  }
})
